package com.my.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.constant.GatewayConstant;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author coderMy
 * @Date 2021/3/30
 */
@Configuration
public class TokenCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getPath().value();
        //1.如果是登录,或者放行接口,直接放行
        if (GatewayConstant.ALLOW_URLS.contains(uri)){
            return chain.filter(exchange);
        }

        //2.验证header中是否有token,redis中是否存在,但是不能验证jwt的正确性,正确性依然交给各个服务的oauth来解析
        List<String> headers = request.getHeaders().get(GatewayConstant.TOKEN_HEADER_KEY);
        if (!CollectionUtils.isEmpty(headers)){
            String jwt = request.getHeaders().get(GatewayConstant.TOKEN_HEADER_KEY).get(0);
            if (StringUtils.hasText(jwt)){
                jwt = jwt.replaceAll(GatewayConstant.TOKEN_PREFIX_TAG,"");
                //header有token,且redis中也有,放行
                if (StringUtils.hasText(jwt) && stringRedisTemplate.hasKey(GatewayConstant.TOKEN_REDIS_PREFIX+jwt)){
                    chain.filter(exchange);
                }
            }
        }

        //3. 走到这,说明没有token,返回未授权
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type","application/json;charset");
        Map<String,Object> res = new HashMap<>();
        res.put("code", HttpStatus.UNAUTHORIZED.value());
        res.put("msg","未授权");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
